package com.authine.cloudpivot.ext.service.impl;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.enums.order.OrderTypeEnum;
import com.authine.cloudpivot.ext.service.OrderCustomerBaseTempV1Service;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.vo.CustomerOrderV1VO;
import com.authine.cloudpivot.ext.vo.OrderGoodsV1VO;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liwei
 * @DateTime: 2021/10/22
 * @Description: TODO
 */
public class OrderCustomerBaseTempV1ServiceImpl implements OrderCustomerBaseTempV1Service {

    @Override
    public List<Map<String, Object>> findByQuotationIds(List<String> quotationGoodsIds) {
        //    @Query("select g from GoodsPurchaseEntity g where g.quotationGoods.id in (?1)")
        //组织采购表
        String goodsPurchaseTable = JdbcTemplateUtils.getTableName(ModelConst.T_GOODS_PURCHASE, AppConst.COMMODITYMATERIALS);
        //报价商品表
        String quotationGoodsTable = JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS, AppConst.SOURCING_CENTER);

        return JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE).selectField("*").in("quotation_goods_id", quotationGoodsIds).queryForList();
    }

    @Override
    public List<Map<String, Object>> getCanPlaceOrder(List<String> goodsIds) {

        if (CollectionUtils.isEmpty(goodsIds)) {
            return Collections.emptyList();
        }



        return null;
    }


    public void after(CustomerOrderV1VO customerOrderV1VO) {

        List<OrderGoodsV1VO> orderGoods = customerOrderV1VO.getOrderGoods();
        List<String> quotationGoodsIds = customerOrderV1VO.getOrderGoods().stream().filter(e -> e.getSrc() != 4).map(e -> e.getQuotationGoodsId()).collect(Collectors.toList());

        List<Map<String, Object>> goodsPurchaseList = findByQuotationIds(quotationGoodsIds);

        List<Map<String, Object>> needUpdateGoodsPurchaseList = new ArrayList<>();
        boolean flag = false;
        for (OrderGoodsV1VO orderGood : customerOrderV1VO.getOrderGoods()) {

            if (orderGood.getSrc() != 4) {

                if (CollectionUtils.isEmpty(goodsPurchaseList)) {
                    //throw new OrderException("未获取到需要回写的企业采购商品");
                }
                Map<String, Object> goodsPurchase = goodsPurchaseList.stream().filter(e -> e.get("").equals(orderGood.getQuotationGoodsId())).findFirst().orElseThrow(null);

                Assert.isTrue(null != goodsPurchase, " 未获取到对应的采购单数据 ！ ");

                Map<String, Object>  updateMap = new HashMap<>();
                updateMap.put("id",goodsPurchase.get("id"));
                if (orderGood.getSrc() == 2) {
                    updateMap.put("enabled", false);
                    updateMap.put("bought", orderGood.getNum());

                } else if (orderGood.getSrc() == 3) {
                    BigDecimal bought = goodsPurchase.get("bought") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(goodsPurchase.get("bought")));
                    updateMap.put("bought", orderGood.getNum().add(bought));
                    //第二次采购不限制最大采购量
                    updateMap.put("maximum", null);
                }
                needUpdateGoodsPurchaseList.add(updateMap);

            } else if (orderGood.getSrc() == 4) {
                flag = true;
            }
        }

        if (flag){
            //todo 是否只用更新客户订单？供应商是否需要考虑？  枚举类型有疑问？ customerOrderEntity.setOrderType(OrderTypeEnum.ExternalMallOrders);
            Map<String, Object>  customerOrderMap = new HashMap<>();
            customerOrderMap.put("id",customerOrderV1VO.getOrderGoods().get(0).getCustomerOrderId());
            customerOrderMap.put("type", OrderTypeEnum.ClientOrder);
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_ORDER_CUSTOMER, customerOrderMap);
        }

        if (!CollectionUtils.isEmpty(goodsPurchaseList)) {
            //iGoodsPurchaseRepository.saveAll(goodsPurchaseList);
            String goodsPurchaseTable = JdbcTemplateUtils.getTableName(ModelConst.T_GOODS_PURCHASE, AppConst.COMMODITYMATERIALS);
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(goodsPurchaseTable, needUpdateGoodsPurchaseList);
        }

    }
}
